package com.jxtti.controller;

import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jxtti.entity.Admin_RoleType;
import com.jxtti.entity.Admin_UserRole;
import com.jxtti.model.User;
import com.jxtti.service.AdminRoleTypeService;
import com.jxtti.service.AdminUserRoleService;
import com.jxtti.service.DistrictService;
import com.jxtti.service.UserService;
import com.jxtti.utils.AuthUtil;
import com.jxtti.utils.Constants;
import com.jxtti.utils.CookieUtil;
import com.jxtti.utils.ExceptionUtil;

@Controller
@RequestMapping("/AdminUser") 
public class AdminUserController {
	private final static Logger log= Logger.getLogger(AdminUserController.class);
			
	@Autowired
	private CookieUtil cookieUtil;
	
	@InitBinder 
    public void initBinder(WebDataBinder binder) {     
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");     
        dateFormat.setLenient(false);     
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }	
	
	
	@Autowired
	private UserService userService; 
	
	@Autowired 
	private AdminUserRoleService  adminUserRoleService; 
	
	@Autowired 
	private AdminRoleTypeService  adminRoleTypeService; 
	
	@Autowired
	private DistrictService districtService;
	
	//登录系统
	@RequestMapping(value = "/login")
	public String login(User loginUser,HttpServletRequest request, HttpServletResponse response){
		ModelAndView  mav = new ModelAndView();
		User user = userService.findUserByName(loginUser.getUserName());
		if (user != null&& user.getPassword().equals(loginUser.getPassword())) {
			Map<String, String> gzdata =new HashMap<String, String>();
			gzdata.put("id",user.getOrgId().toString());
			String orgName=districtService.getFullNameById(gzdata);
			user.setOrgName(orgName);

			//查询用户对应网站的角色
			Map<String, Object> dataWeb = new HashMap<String,Object>();	
			dataWeb.put("fk_UserId", user.getId());			
			dataWeb.put("is_deleted",0);	
			dataWeb.put("status",1);
			List<Admin_UserRole> userRoleWeb=adminUserRoleService.queryAll(dataWeb);
			if (userRoleWeb!=null&&!userRoleWeb.isEmpty()){
				Admin_UserRole admin_userRole=userRoleWeb.get(0);
				user.setRoleId(admin_userRole.getFk_RoleType());
				user.setOrgName(admin_userRole.getRoleName());
				Admin_RoleType admin_roleType=adminRoleTypeService.queryListById(admin_userRole.getFk_RoleType());
				user.setDistrictId(String.valueOf(admin_roleType.getIsAdmin()));
			}
			AuthUtil.setUser(request, user);
			if ("on".equals(request.getParameter("autoLogin"))) {
				// 写入cookie				 
				cookieUtil.saveCookie(user, response);
			}			
			return "/pages/Admin/main.jsp";
		}else{
			if (null != AuthUtil.getUserInfo(request)) {
				return "/pages/Admin/main.jsp";
			} else {
				request.getSession().invalidate();
				return "redirect:/login.jsp";
			}		
		}
	}
	
	@RequestMapping(value = "/getCurrentUserInfo", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getCurrentUserInfo(
			@RequestParam Map<String, String> data, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			User userInfo = AuthUtil.getUserInfo(request);
			if (null != userInfo) {
				result.put("userInfo", userInfo);
				result.put("success", true);
			} else {
				result.put("success", false);
			}
		} catch (Exception e) {
			result.put("success", false);
			result.put("error", ExceptionUtil.createStackTrackMessage(e)); 
			e.printStackTrace();
		}

		return result;
	}
	
	//退出系统
	@RequestMapping(value = "/logout")
	@ResponseBody
	public Map<String, Object> logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		cookieUtil.clearCookie(response);// cookie清除
		request.getSession().invalidate();// session失效
		result.put("redirectURL", Constants.SYSTEM_PATH);
		return result;
	}
	
	//登录主页---bff
	@RequestMapping(value = "/mainInterface")
	@ResponseBody
	public ModelAndView mainInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/main.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
		
	//用户列表页面
	@RequestMapping(value = "/listInterface")
	@ResponseBody
	public ModelAndView listUserInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/UserAndRole/UsersList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	

	/**
	 * 获取用户信息列表
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getUserList", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getMenuList(
			@RequestParam Map<String, String> data, HttpServletRequest request,
			HttpServletResponse response) {		
		Map<String, Object> result = new HashMap<String, Object>();
		// 第几页
		int pageNum = Integer.parseInt((data.get("page") == null || data.get(
				"page").equals("0")) ? "1" : data.get("page"));
		// 每页显示条数 
		int pageSize = Integer.parseInt((data.get("rows") == null || data.get(
				"rows").equals("0")) ? "10" : data.get("rows"));
		PageHelper.startPage(pageNum, pageSize);
		
		String fk_RoleType=data.get("roleType").toString(); //角色名称
		
		//调用 统一认证
		//DbContextHolder.setDbType(DataSourceConst.SLAVE); //调用service之前只需要设置上下文 调用相应的数据源			
		List<User> userListAll=userService.getUserListForWeb(data);			
		//DbContextHolder.clearDbType();
		//判断用户 在网站中是否有 角色 --该角色下的用户，和没有角色的用户
		for(int i=0;i<userListAll.size();i++){			
			Map<String, Object> dataWeb = new HashMap<String,Object>();			
			dataWeb.put("fk_UserId", userListAll.get(i).getId());						
			List<Admin_UserRole> userRoleWeb=adminUserRoleService.queryAll(dataWeb);
			
//			if(userRoleWeb.size()==0||userRoleWeb==null){
//				userListAll.get(i).setRoleId(null);
//				userListAll.get(i).setRoleName(null);				
//			}else if (userRoleWeb.get(0).getFk_RoleType()==Integer.parseInt(fk_RoleType)){
//				userListAll.get(i).setRoleId(userRoleWeb.get(0).getFk_RoleType());				
//				userListAll.get(i).setRoleName(userRoleWeb.get(0).getRoleName());
//			}else{ //从list中删除这一项				
//				userListAll.remove(i); 
//				i--;
//			}		
			
			if(userRoleWeb.size()==0||userRoleWeb==null){
				userListAll.get(i).setRoleId(null);
				userListAll.get(i).setRoleName(null);				
			}else{
				userListAll.get(i).setRoleId(userRoleWeb.get(0).getFk_RoleType());				
				userListAll.get(i).setRoleName(userRoleWeb.get(0).getRoleName());
			}	
		}
		
		PageInfo<User> userPage = new PageInfo<User>(userListAll);
					
		result.put("total", userPage.getTotal());
		result.put("rows", userPage.getList());

		return result;
	}
			
	@RequestMapping(value = "/addInterface")
	@ResponseBody 
	public ModelAndView addInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/UserAndRole/EditUser.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}	
		
}
